package com.caocaog.market.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.baidu.BaiduTextContentCheck;
import com.caocaog.market.constant.MarketConstant;
import com.caocaog.market.entity.Information;
import com.caocaog.market.entity.InformationDetail;
import com.caocaog.market.mapper.InformationMapper;
import com.caocaog.market.service.InformationDetailService;
import com.caocaog.market.service.InformationReplyService;
import com.caocaog.market.service.InformationService;
import com.caocaog.market.vo.InformationVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.CheckFailedException;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 信息发布
 *
 * @author chechen
 * @date 2021-11-13
 */
@Service
@Transactional
@RequiredArgsConstructor
public class InformationServiceImpl extends ServiceImpl<InformationMapper, Information> implements InformationService {

    private final InformationReplyService informationReplyService;
    private final InformationDetailService informationDetailService;

    @Override
    public IPage<InformationVO> queryInformationPage(Page<InformationVO> page, Information information) {
        this.handleInformationByUserType(information, (LoginUser) SecurityUtils.getSubject().getPrincipal());
        return super.baseMapper.queryInformationPage(page, information);
    }

    @Override
    public IPage<InformationVO> queryInformationPageAllApproved(Page<InformationVO> page, Information information) {
        information.setStatus(3); // 只查审核通过的
        if (StringUtils.isBlank(information.getSiteId()))
            throw new CheckFailedException("分站id不能为空");
        return super.baseMapper.queryInformationPage(page, information);
    }

    @Override
    public IPage<InformationVO> queryInformationPageAllYourSelf(Page<InformationVO> page, Information information) {
        if (StringUtils.isBlank(information.getCreateBy()))
            throw new CheckFailedException("创建人不能为空");
        return super.baseMapper.queryInformationPage(page, information);
    }

    @Override
    public InformationVO getDetailById(String id) {
        Information informationById = super.baseMapper.selectById(id);
        InformationDetail informationDetailById = this.informationDetailService.getById(id);

        if (informationById.getId() == null || informationDetailById.getId() == null)
            throw new JeecgBootException("获取信息失败, id-> " + id);
        return new InformationVO()
                .setInformation(informationById)
                .setInformationDetail(informationDetailById);
    }

    @Override
    public String addInformation(InformationVO informationVO) {
        Information information = informationVO.toInformation();
        InformationDetail informationDetail = informationVO.toInformationDetail();

        if (information.getSiteId() == null) {
            throw new CheckFailedException("分站id不能为空");
        } else if (StringUtils.isBlank(information.getCreateBy())) {
            throw new CheckFailedException("创建人不能为空");
        }

        // 新增前处理一下数据
        // 新增信息发布（information）
        information.setCreateTime(new Date());
        information.setDelFlag(CommonConstant.DEL_FLAG_0);
        information.setLockVersion(1);
        information.setReadQty(0);
        information.setReplyQty(0);
        information.setStatus(1); // 默认为待审核状态
        information.setUpShelf(0); // 默认为上架状态
        super.baseMapper.insert(information);

        // 新增信息发布内容（InformationDetail）
        informationDetail.setId(information.getId());
        this.informationDetailService.save(informationDetail);

        if (information.getId() == null)
            throw new JeecgBootException("新增信息失败");
        return information.getId();
    }

    /**
     * 根据用户类型处理信息发布实体数据
     *
     * @param information 信息发布实体
     * @param loginUser   当前登录用户
     */
    private void handleInformationByUserType(Information information, LoginUser loginUser) {
        // 根据用户类型判断
        if (MarketConstant.USER_TYPE_SITE.equals(loginUser.getUserType())) {
            if (StringUtils.isBlank(loginUser.getSiteId()))
                throw new JeecgBootException("用户暂未绑定分站, realName-> " + loginUser.getRealname());
            // 分站类型默认 查询该分站下的数据/插入分站
            information.setSiteId(loginUser.getSiteId());
        }
    }

    @Override
    public int updateInformation(InformationVO informationVO) {
        Information information = informationVO.toInformation();
        InformationDetail informationDetail = informationVO.toInformationDetail();

        // 更新前处理一下数据
        if (StringUtils.isBlank(information.getUpdateBy()))
            throw new CheckFailedException("更新人id（updateBy）不能为空");
        information.setUpdateTime(new Date());
        information.setDelFlag(null);

        // 状态（status）只能在 [已驳回] 的状态下修改
        Information currentInformation = this.selectInformationById(information.getId());
        if (currentInformation.getStatus() != 2)
            throw new JeecgBootException("只能在 [已驳回] 的状态下编辑");

        this.informationDetailService.updateById(informationDetail);
        int updateRecordCount = super.baseMapper.updateById(information);
        if (updateRecordCount == 0)
            throw new JeecgBootException("更新信息失败, id-> " + information.getId());
        return updateRecordCount;
    }

    @Override
    public int updateAndSubmitReviewInformation(InformationVO informationVO) {
        int updateRecordCount = this.updateInformation(informationVO);
        int submitReviewRecordCount = this.submitReview(informationVO.getId());
        return updateRecordCount + submitReviewRecordCount;
    }

    @Override
    public int putOnSaleInfo(String id) {
        int putOnSaleRecordCount = this.upDownInfo(0, id);
        if (putOnSaleRecordCount == 0)
            throw new JeecgBootException("信息上架失败, id-> " + id);
        return putOnSaleRecordCount;
    }

    @Override
    public int pullOffShelvesInfo(String id) {
        int pullOffShelvesRecordCount = this.upDownInfo(1, id);
        if (pullOffShelvesRecordCount == 0)
            throw new JeecgBootException("信息下架失败, id-> " + id);
        return pullOffShelvesRecordCount;
    }

    private int upDownInfo(Integer upShelf, String id) {
        return super.baseMapper.update(null, Wrappers.<Information>lambdaUpdate()
                .set(Information::getUpShelf, upShelf).eq(Information::getId, id));
    }

    @Override
    public int submitReview(String id) {
        // 判断当前信息的创建人id，与当前登录人id是否不一致
        /*if (!this.selectInformationById(id).getId()
                .equals(((LoginUser) SecurityUtils.getSubject().getPrincipal()).getId()))
            throw new JeecgBootException("只有本人才能提交审核");*/

        int submitReviewRecordCount = this.changeStatus(id, 1);
        if (submitReviewRecordCount == 0)
            throw new JeecgBootException("信息提交审核操作失败, id-> " + id);
        return submitReviewRecordCount;
    }

    @Override
    public int approvedReview(String id) {
        // 检查
        InformationVO information = this.getDetailById(id);
        String res = BaiduTextContentCheck.textCensor(StringUtils.join(information.getName(), information.getContent(), StringPool.COMMA));
        JSONObject obj = JSONUtil.parseObj(res);
        Integer status = (Integer)obj.get("status");
        String message = (String)obj.get("msg");
        if (status != 1) {
            String errorMessage = "检测出错，请稍后重试";
            if (status == 2 || status == 3) {
                errorMessage = message;
            }
            throw new JeecgBootException(errorMessage);
        }

        int approvedReviewRecordCount = this.changeStatus(id, 3);
        if (approvedReviewRecordCount == 0)
            throw new JeecgBootException("信息审核通过操作失败, id-> " + id);
        return approvedReviewRecordCount;
    }

    @Override
    public int notApprovedReview(String id) {
        int notApprovedReviewRecordCount = this.changeStatus(id, 2);
        if (notApprovedReviewRecordCount == 0)
            throw new JeecgBootException("信息审核不通过操作失败, id-> " + id);
        return notApprovedReviewRecordCount;
    }

    private int changeStatus(String id, Integer value) {
        return super.baseMapper.update(null, new LambdaUpdateWrapper<Information>()
                .set(Information::getStatus, value)
                .eq(Information::getId, id));
    }

    @Override
    public int deleteInformation(String id) {
        // 删除要顺带删除评论
        this.informationReplyService.deleteInformationReplyByInfoId(id);
        int deleteRecordCount = super.baseMapper.deleteById(id);
        if (deleteRecordCount == 0)
            throw new JeecgBootException("删除信息失败, id-> " + id);
        return deleteRecordCount;
        // P.S. informationDetail表没有逻辑删除字段，所以没必要删，下面的批量删除（deleteBatchInformation）同理
    }

    @Override
    public int deleteBatchInformation(List<String> ids) {
        this.informationReplyService.deleteBatchInformationReplyByInfoIds(ids);
        int deleteRecordCount = super.baseMapper.deleteBatchIds(ids);
        if (deleteRecordCount < ids.size())
            throw new JeecgBootException(
                    String.format("批量删除信息失败, deleteRecordCount-> %s, ids.size()-> %s, ids-> %s",
                            deleteRecordCount, ids.size(), ids));
        return deleteRecordCount;
    }

    @Override
    public void readQtyPlusOne(String id) {
        super.baseMapper.update(null, new LambdaUpdateWrapper<Information>()
                .setSql("read_qty = read_qty + 1")
                .eq(Information::getId, id));
    }

    @Override
    public void replyQtyPlusOne(String id) {
        super.baseMapper.update(null, new LambdaUpdateWrapper<Information>()
                .setSql("reply_qty = reply_qty + 1")
                .eq(Information::getId, id));
    }

    @Override
    public void replyQtyMinusNum(String id, Integer num) {
        super.baseMapper.update(null, new LambdaUpdateWrapper<Information>()
                .setSql("reply_qty = reply_qty - " + num)
                .eq(Information::getId, id));
    }

    private Information selectInformationById(String id) {
        Information information = super.baseMapper.selectById(id);
        if (information == null)
            throw new JeecgBootException("查询不到此id对应的信息, id-> " + id);
        return information;
    }

}
